#include<graphics.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

#pragma comment(lib,"Winmm.lib")
#define High 600
#define Width 350


IMAGE  img_BK,img_bd1,img_bd2,img_bar_up1,img_bar_up2,img_bar_down1,img_bar_down2;//定义全局变量
int bird_x,bird_y;
int bar_x,bar_up_y,bar_down_y,bar_speed;
int score=0;
char s[5];

void startup()
{
	mciSendString("open C:\\background.mp3 alias bkmusic",NULL, 0, NULL);//背景音乐
	mciSendString("play bkmusic repeat",NULL, 0, NULL);//循环播放
	
	initgraph(350,600);

	loadimage(&img_BK,"C:\\background.jpg"); //读取图片位置
	loadimage(&img_bd1,"C:\\bird1.jpg");
	loadimage(&img_bd2,"C:\\bird2.jpg");
	loadimage(&img_bar_up1,"C:\\bar_up1.gif");
	loadimage(&img_bar_up2,"C:\\bar_up2.gif");
	loadimage(&img_bar_down1,"C:\\bar_down1.gif");
	loadimage(&img_bar_down2,"C:\\bar_down2.gif   ");
	
	bird_x = 50;
	bird_y = 200;

	bar_x = 150;
	bar_up_y = 400;
	bar_down_y = 400;
	bar_speed = 5;

	system("pause");

	BeginBatchDraw();
}
void show()//显示画面
{
	putimage(0,0,&img_BK);//在坐标（0，0）显示背景
	putimage(bird_x,bird_y,&img_bd1,NOTSRCERASE);
	putimage(bird_x,bird_y,&img_bd2,SRCINVERT);//显示小鸟
	putimage(bar_x,-bar_up_y,&img_bar_up1,NOTSRCERASE);
	putimage(bar_x,-bar_up_y,&img_bar_up2,SRCINVERT);//显示上一半障碍物
	putimage(bar_x,bar_down_y,&img_bar_down1,NOTSRCERASE);
	putimage(bar_x,bar_down_y,&img_bar_down2,SRCINVERT);//显示下一段障碍物
	outtextxy(255,50,"得分：");
	sprintf(s,"%d",score);
	outtextxy(300,50,s);//输出得分
	
	FlushBatchDraw();
	Sleep(50);
}
void updateWithoutInput()//与用户输入无关的更新			
{
	if (bird_y<580)
	{
		bird_y += 8;
	}

	if (bar_x<-80)
	{
		bar_x = Width+50;
		bar_up_y = rand()%300+200;
		bar_down_y = 800-bar_up_y;
	}
	else
	{
		bar_x = bar_x-bar_speed;	
	}

	if (bird_x>=bar_x-40 && bird_x<=bar_x + 40)//判断是否撞上
	{
		if (bird_y<=600-bar_up_y||bird_y>=bar_down_y)
		{
			exit(0);
		}
	}
	if (bird_x>bar_x+34+bar_speed && bird_x<bar_x+44+bar_speed)
	{
		score++;
	}
	if (score%10 == 1 && bar_speed < 15)
	{
		score++;
		bar_speed += 2;
	}
}
		
void updateWithInput()//与用户输入有关的更新
{
	char input;
	if (kbhit())
	{
		input = getch();
		if (input ==' ' && bird_y>20)
		{
			bird_y = bird_y-60;
			mciSendString("close jpmusic",NULL, 0, NULL);//先把前面一次的音乐关闭
			mciSendString("open C:\\Jump.mp3 alias jpmusic",NULL, 0, NULL);//跳高音乐
			mciSendString("play jpmusic",NULL, 0, NULL);//播放一次
		}
	}
}
void gameover()
{
	EndBatchDraw();
	getch();
	closegraph();
}

int main() 
{
	startup();//数据初始化
    while(1)//游戏循环执行
	{
		show();//显示画面
		updateWithoutInput();//与用户输入无关的更新
		updateWithInput();//与用户输入有关的更新
	}
	gameover();
	return 0;
}
